<template>
  <el-row :gutter="0" class="login-form">
    <el-col :span="24">
      <el-form
        ref="loginFormRef"
        label-width="auto"
        :model="loginForm"
        :size="'large'"
        :rules="loginRules"
        @keyup.enter="login"
      >
        <el-form-item prop="username">
          <el-input
            type="text"
            name="username"
            placeholder="邮箱/手机号码/小米ID"
            v-model="loginForm.username"
            prefix-icon="User"
            clearable
            :maxlength="50"
            @input="handleInput"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            name="password"
            placeholder="密码"
            v-model="loginForm.password"
            prefix-icon="Lock"
            show-password
            :maxlength="20"
            @input="handleInput"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="submit-btn"
            @click="login"
            :loading="loading"
            :disabled="buttonDisabled"
            color="#ff6700"
            >登录</el-button
          >
        </el-form-item>
        <div class="form-footer">
          <router-link :to="registerPage"> 立即注册 </router-link>
          <span class="divider">|</span>
          <router-link to="/auth/forgot-password">忘记密码？</router-link>
        </div>
      </el-form>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted } from "vue";
  import { useRouter } from "vue-router";
  import httpClient from "../../../utils/http";
  import type { FormRules, FormInstance } from "element-plus";
  import { ElMessage } from "element-plus";

  interface LoginForm {
    username: string;
    password: string;
  }

  const loginFormRef = ref<FormInstance>();
  const loading = ref(false);

  const loginForm = reactive<LoginForm>({
    username: "",
    password: "",
  });

  const registerPage = {
    path: "/auth",
    query: { type: "register" },
  };

  const loginRules = reactive<FormRules>({
    username: [
      { required: true, message: "请输入用户名", trigger: "blur" },
      {
        min: 3,
        max: 50,
        message: "用户名长度应在3-50个字符之间",
        trigger: "blur",
      },
    ],
    password: [
      { required: true, message: "请输入密码", trigger: "blur" },
      {
        min: 6,
        max: 20,
        message: "密码长度应在6-20个字符之间",
        trigger: "blur",
      },
    ],
  });

  const router = useRouter();

  const buttonDisabled = computed(() => {
    return !loginForm.username || !loginForm.password || loading.value;
  });

  const handleInput = () => {
    loginFormRef.value?.clearValidate();
  };

  const login = async () => {
    if (loading.value) return;

    try {
      loading.value = true;
      const valid = await loginFormRef.value?.validate();

      if (!valid) {
        ElMessage({
          type: "error",
          message: "请填写正确的登录信息",
          offset: 80,
        });
        return;
      }

      const res = await httpClient.post("/auth/login", {
        username: loginForm.username,
        password: loginForm.password,
      });

      if (res.status === 200) {
        localStorage.setItem("userName", loginForm.username);
        localStorage.setItem("userInfo", "user was login");
        ElMessage({
          type: "success",
          message: "登录成功",
          offset: 80,
        });
        router.push("/shop");
      }
    } catch (error) {
      ElMessage({
        type: "error",
        message: "登录失败，请稍后重试",
        offset: 80,
      });
    } finally {
      loading.value = false;
    }
  };

  onMounted(() => {
    loginFormRef.value?.resetFields();
  });
</script>

<style lang="scss" scoped>
  @use "sass:color";
  @use "@/styles/variable" as *;

  .login-form {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 20px;
    padding: 20px;
  }

  .submit-btn {
    width: 100%;
    height: 40px;
    font-size: 16px;
    color: $bsWhite;
    transition: all 0.3s ease;

    &:hover {
      opacity: 0.9;
    }

    &:active {
      transform: scale(0.98);
    }
  }

  :deep(.el-input--large .el-input__wrapper) {
    padding: 6px 15px;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 0 0 1px $themeColor inset;
    }

    &.is-focus {
      box-shadow: 0 0 0 1px $themeColor inset;
    }
  }

  .form-footer {
    text-align: center;
    margin-top: 20px;
    font-size: 14px;
    color: #666;

    a {
      color: $themeColor;
      text-decoration: none;
      transition: color 0.3s ease;

      &:hover {
        color: color.scale($themeColor, $lightness: -10%);
      }
    }

    .divider {
      margin: 0 10px;
      color: #ddd;
    }
  }
</style>
